//
//  CaculateViewController.m
//  TestIos
//
//  Created by HsDev on 2025/1/21.
//  Copyright © 2025 Liyadong. All rights reserved.
//  算法调试

#import "CaculateViewController.h"


// 打印数组的函数
void printArray(NSArray *array) {
    for (NSNumber *num in array) {
        NSLog(@"%ld ", (long)[num intValue]);
    }
    NSLog(@"\n");
}
 
// 插入排序函数
void insertionSort(NSMutableArray *array) {
    NSUInteger count = [array count];
    for (NSUInteger i = 1; i < count; i++) {
        NSNumber *key = array[i];
        int j = i - 1;
        
        // 将key插入到已排序部分的正确位置
        while (j >= 0 && [array[j] intValue] > [key intValue]) {
            NSLog(@"当前要排序 %d,判断%d比%d大，所以要把 %d放到 %d", [key intValue], [array[j] intValue], [key intValue], [array[j] intValue], j + 1);
            array[j + 1] = array[j];
            j--;
            
        }
        array[j + 1] = key;
        NSLog(@"sort j info : %d, %d, %@",i, j, key);

        printArray(array);
        
    }
}

@interface CaculateViewController ()

@end

@implementation CaculateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self insertionSortTest];
}

/**
 插入排序调试
 */

- (void)insertionSortTest {
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@5, @2, @9, @1, @5, @6, nil];
            
            NSLog(@"排序前的数组: ");
            printArray(array);
            
            insertionSort(array);
            
            NSLog(@"排序后的数组: ");
            printArray(array);
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
